<template>
  <view class="dispute-detail-container">

    <!-- 纠纷状态卡片 -->
    <view class="status-card">
      <view class="status-header">
        <view class="status-icon" :class="getStatusClass(disputeInfo.status)">
          <text class="icon">{{ getStatusIcon(disputeInfo.status) }}</text>
        </view>
        <view class="status-content">
          <text class="status-title">{{ disputeInfo.title || '纠纷处理通知' }}</text>
          <text class="status-text">{{ getStatusText(disputeInfo.status) }}</text>
        </view>
      </view>
      <view class="status-time">
        <text class="time-label">处理时间：</text>
        <text class="time-value">{{ formatTime(disputeInfo.processTime) }}</text>
      </view>
    </view>

    <!-- 纠纷详情 -->
    <view class="detail-card">
      <view class="card-header">
        <text class="card-title">处理详情</text>
      </view>
      <view class="detail-content">
        <text class="content-text">{{ disputeInfo.content || '您的纠纷已由管理员处理完成' }}</text>
      </view>
    </view>

    <!-- 相关任务信息 -->
    <view class="task-card" v-if="disputeInfo.relatedTask">
      <view class="card-header">
        <text class="card-title">相关任务</text>
      </view>
      <view class="task-info" @click="viewTask">
        <view class="task-content">
          <text class="task-title">{{ disputeInfo.relatedTask.title || '相关任务' }}</text>
          <text class="task-desc">{{ disputeInfo.relatedTask.description || '点击查看任务详情' }}</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
    </view>

    <!-- 处理结果 -->
    <view class="result-card" v-if="disputeInfo.result">
      <view class="card-header">
        <text class="card-title">处理结果</text>
      </view>
      <view class="result-content">
        <view class="result-item" v-for="(item, index) in disputeInfo.result" :key="index">
          <view class="result-label">{{ item.label }}：</view>
          <view class="result-value">{{ item.value }}</view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons" v-if="disputeInfo.actions && disputeInfo.actions.length > 0">
      <button 
        v-for="action in disputeInfo.actions" 
        :key="action.type"
        class="action-btn"
        :class="action.type"
        @click="handleAction(action)"
      >
        {{ action.text }}
      </button>
    </view>

    <!-- 申诉入口 -->
    <view class="appeal-section" v-if="canAppeal">
      <view class="appeal-tip">
        <text class="tip-text">如对处理结果有异议，可在{{ remainingAppealDays }}天内提起申诉</text>
      </view>
      <button class="appeal-btn" @click="submitAppeal">
        提起申诉
      </button>
    </view>

    <!-- 时间线 -->
    <view class="timeline-card" v-if="disputeInfo.timeline && disputeInfo.timeline.length > 0">
      <view class="card-header">
        <text class="card-title">处理进度</text>
      </view>
      <view class="timeline">
        <view 
          v-for="(item, index) in disputeInfo.timeline" 
          :key="index"
          class="timeline-item"
          :class="{ 'active': item.completed }"
        >
          <view class="timeline-dot"></view>
          <view class="timeline-content">
            <text class="timeline-title">{{ item.title }}</text>
            <text class="timeline-time">{{ formatTime(item.time) }}</text>
            <text class="timeline-desc" v-if="item.description">{{ item.description }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      disputeId: '',
      disputeInfo: {
        id: '',
        title: '',
        content: '',
        status: 'resolved', // pending, processing, resolved, rejected, appealed
        processTime: '',
        relatedTask: null,
        result: [],
        actions: [],
        timeline: []
      },
      canAppeal: false,
      remainingAppealDays: 7
    }
  },
  onLoad(options) {
    this.disputeId = options.id || options.relatedId || '';
    
    // 如果是从通知跳转过来的
    if (options.notificationData) {
      try {
        const notificationData = JSON.parse(decodeURIComponent(options.notificationData));
        this.processNotificationData(notificationData);
      } catch (e) {
        console.error('解析通知数据失败:', e);
      }
    }
    
    this.loadDisputeDetail();
  },
  methods: {

    // 处理通知数据
    processNotificationData(notificationData) {
      this.disputeInfo = {
        ...this.disputeInfo,
        id: notificationData.id || this.disputeId,
        title: notificationData.title || '纠纷处理通知',
        content: notificationData.content || '',
        processTime: notificationData.create_time || new Date(),
        status: this.getStatusFromNotification(notificationData)
      };
    },

    // 从通知数据推断状态
    getStatusFromNotification(notificationData) {
      if (notificationData.content && notificationData.content.includes('处理完成')) {
        return 'resolved';
      } else if (notificationData.content && notificationData.content.includes('处理中')) {
        return 'processing';
      }
      return 'resolved';
    },

    // 加载纠纷详情
    async loadDisputeDetail() {
      try {
        // 如果没有具体的纠纷ID，显示默认信息
        if (!this.disputeId) {
          this.setDefaultDisputeInfo();
          return;
        }

        // 调用云函数获取纠纷详情
        const result = await uniCloud.callFunction({
          name: 'getDisputeDetail',
          data: {
            disputeId: this.disputeId
          }
        });

        if (result.result && result.result.success) {
          this.disputeInfo = {
            ...this.disputeInfo,
            ...result.result.data
          };
          this.checkAppealStatus();
        } else {
          // 如果获取失败，显示默认信息
          this.setDefaultDisputeInfo();
        }
      } catch (error) {
        this.setDefaultDisputeInfo();
      }
    },

    // 设置默认纠纷信息
    setDefaultDisputeInfo() {
      this.disputeInfo = {
        ...this.disputeInfo,
        title: '任务纠纷处理结果',
        content: '您发布的任务"系统通知"的纠纷已由管理员处理，处理结果：任务时间已延长7天',
        status: 'resolved',
        processTime: new Date(),
        result: [
          { label: '处理结果', value: '任务时间延长7天' },
          { label: '责任方', value: '平台协调处理' },
          { label: '处理人员', value: '系统管理员' }
        ],
        timeline: [
          {
            title: '纠纷提交',
            time: Date.now() - 7 * 24 * 60 * 60 * 1000,
            completed: true,
            description: '用户提交纠纷申请'
          },
          {
            title: '管理员受理',
            time: Date.now() - 5 * 24 * 60 * 60 * 1000,
            completed: true,
            description: '管理员开始处理纠纷'
          },
          {
            title: '调查取证',
            time: Date.now() - 3 * 24 * 60 * 60 * 1000,
            completed: true,
            description: '收集相关证据和信息'
          },
          {
            title: '纠纷处理完成',
            time: Date.now() - 1 * 24 * 60 * 60 * 1000,
            completed: true,
            description: '纠纷已处理完成，任务时间延长'
          }
        ]
      };
      this.checkAppealStatus();
    },

    // 检查申诉状态
    checkAppealStatus() {
      const processTime = new Date(this.disputeInfo.processTime).getTime();
      const now = Date.now();
      const daysDiff = Math.floor((now - processTime) / (24 * 60 * 60 * 1000));
      
      this.canAppeal = daysDiff < 7 && this.disputeInfo.status === 'resolved';
      this.remainingAppealDays = Math.max(0, 7 - daysDiff);
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        pending: 'status-pending',
        processing: 'status-processing', 
        resolved: 'status-resolved',
        rejected: 'status-rejected',
        appealed: 'status-appealed'
      };
      return classMap[status] || 'status-default';
    },

    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        pending: '⏳',
        processing: '⚙️',
        resolved: '✅',
        rejected: '❌',
        appealed: '📋'
      };
      return iconMap[status] || '📄';
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        pending: '等待处理',
        processing: '处理中',
        resolved: '已处理完成',
        rejected: '申请被拒绝',
        appealed: '申诉中'
      };
      return textMap[status] || '未知状态';
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      
      try {
        const date = new Date(time);
        if (isNaN(date.getTime())) return '';
        
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (e) {
        return '';
      }
    },

    // 查看相关任务
    viewTask() {
      if (!this.disputeInfo.relatedTask || !this.disputeInfo.relatedTask.id) {
        uni.showToast({
          title: '任务信息不存在',
          icon: 'none'
        });
        return;
      }

      uni.navigateTo({
        url: `/pages/task/TaskDetail/TaskDetail?id=${this.disputeInfo.relatedTask.id}`
      });
    },

    // 处理操作按钮
    handleAction(action) {
      switch (action.type) {
        case 'confirm':
          this.confirmResult();
          break;
        case 'appeal':
          this.submitAppeal();
          break;
        case 'contact':
          this.contactSupport();
          break;
        default:
          console.log('未知操作:', action);
      }
    },

    // 确认处理结果
    confirmResult() {
      uni.showModal({
        title: '确认处理结果',
        content: '确认接受此次纠纷处理结果？确认后将无法再次申诉。',
        success: (res) => {
          if (res.confirm) {
            this.canAppeal = false;
            uni.showToast({
              title: '已确认处理结果',
              icon: 'success'
            });
          }
        }
      });
    },

    // 提起申诉
    submitAppeal() {
      uni.showModal({
        title: '提起申诉',
        content: '如需申诉，请联系客服或前往申诉页面提交详细申诉材料。',
        confirmText: '联系客服',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.contactSupport();
          }
        }
      });
    },

    // 联系客服
    contactSupport() {
      uni.showActionSheet({
        itemList: ['在线客服', '电话客服', '邮件反馈'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              uni.showToast({ title: '正在为您转接在线客服...', icon: 'none' });
              break;
            case 1:
              uni.makePhoneCall({ phoneNumber: '400-123-4567' });
              break;
            case 2:
              uni.showToast({ title: '客服邮箱：support@campus.com', icon: 'none', duration: 3000 });
              break;
          }
        }
      });
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({
        fail: () => {
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    },

  }
}
</script>

<style scoped>
.dispute-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 40rpx;
  padding-bottom: constant(safe-area-inset-bottom); /* 兼容iOS<11.2 */
  padding-bottom: env(safe-area-inset-bottom); /* 兼容iOS>=11.2 */
}


/* 状态卡片 */
.status-card {
  margin: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
  /* 添加左右安全区域适配 */
  margin-left: calc(24rpx + constant(safe-area-inset-left));
  margin-left: calc(24rpx + env(safe-area-inset-left));
  margin-right: calc(24rpx + constant(safe-area-inset-right));
  margin-right: calc(24rpx + env(safe-area-inset-right));
}

.status-header {
  display: flex;
  align-items: center;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

.status-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
}

.status-resolved {
  background: #f6ffed;
  color: #52c41a;
}

.status-processing {
  background: #e6f7ff;
  color: #1890ff;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-rejected {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-content {
  flex: 1;
}

.status-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.status-text {
  font-size: 28rpx;
  color: #666;
}

.status-time {
  display: flex;
  align-items: center;
  padding-top: 24rpx;
  border-top: 1rpx solid #f0f0f0;
}

.time-label {
  font-size: 26rpx;
  color: #999;
  margin-right: 16rpx;
}

.time-value {
  font-size: 26rpx;
  color: #333;
}

/* 卡片通用样式 */
.detail-card, .task-card, .result-card, .timeline-card {
  margin: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
  /* 添加左右安全区域适配 */
  margin-left: calc(24rpx + constant(safe-area-inset-left));
  margin-left: calc(24rpx + env(safe-area-inset-left));
  margin-right: calc(24rpx + constant(safe-area-inset-right));
  margin-right: calc(24rpx + env(safe-area-inset-right));
}

.card-header {
  padding: 32rpx 32rpx 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 详情内容 */
.detail-content {
  padding: 32rpx;
}

.content-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 任务信息 */
.task-info {
  padding: 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.task-content {
  flex: 1;
}

.task-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.task-desc {
  font-size: 26rpx;
  color: #999;
}

.arrow-icon {
  font-size: 32rpx;
  color: #ccc;
}

/* 处理结果 */
.result-content {
  padding: 32rpx;
}

.result-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16rpx;
}

.result-item:last-child {
  margin-bottom: 0;
}

.result-label {
  font-size: 28rpx;
  color: #666;
  min-width: 160rpx;
}

.result-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

/* 操作按钮 */
.action-buttons {
  margin: 24rpx;
  display: flex;
  gap: 24rpx;
  /* 添加左右安全区域适配 */
  margin-left: calc(24rpx + constant(safe-area-inset-left));
  margin-left: calc(24rpx + env(safe-area-inset-left));
  margin-right: calc(24rpx + constant(safe-area-inset-right));
  margin-right: calc(24rpx + env(safe-area-inset-right));
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.action-btn.confirm {
  background: #1890ff;
  color: #fff;
}

.action-btn.appeal {
  background: #fa8c16;
  color: #fff;
}

.action-btn.contact {
  background: #f0f0f0;
  color: #333;
}

/* 申诉区域 */
.appeal-section {
  margin: 24rpx;
  background: #fff7e6;
  border-radius: 16rpx;
  padding: 32rpx;
  border: 1rpx solid #ffd591;
  /* 添加左右安全区域适配 */
  margin-left: calc(24rpx + constant(safe-area-inset-left));
  margin-left: calc(24rpx + env(safe-area-inset-left));
  margin-right: calc(24rpx + constant(safe-area-inset-right));
  margin-right: calc(24rpx + env(safe-area-inset-right));
}

.appeal-tip {
  margin-bottom: 24rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #fa8c16;
  line-height: 1.5;
}

.appeal-btn {
  width: 100%;
  height: 72rpx;
  background: #fa8c16;
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

/* 时间线 */
.timeline {
  padding: 32rpx;
}

.timeline-item {
  display: flex;
  position: relative;
  padding-bottom: 32rpx;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 12rpx;
  top: 32rpx;
  bottom: -8rpx;
  width: 2rpx;
  background: #e8e8e8;
}

.timeline-item.active::after {
  background: #1890ff;
}

.timeline-dot {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background: #e8e8e8;
  margin-right: 24rpx;
  margin-top: 8rpx;
  flex-shrink: 0;
}

.timeline-item.active .timeline-dot {
  background: #1890ff;
}

.timeline-content {
  flex: 1;
}

.timeline-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.timeline-time {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 8rpx;
}

.timeline-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}
</style>
